package com.mmall.seckill.exception;

import com.mmall.seckill.common.CodeMsg;
import com.mmall.seckill.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by megan on 2018/6/17.
 * 全局异常处理
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobleExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandle(HttpServletRequest httpServletRequest, Exception e){
        log.error("发生异常 -> {}",e);
        if(e instanceof BindException){
            BindException ex = (BindException)e;
            List<ObjectError> errorList =ex.getAllErrors();
            ObjectError error = errorList.get(0);
            String msg = error.getDefaultMessage();
            return Result.coderMsg(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else if(e instanceof GlobalException){
            GlobalException ex = (GlobalException)e;
            return Result.coderMsg(ex.getCodeMsg());
        }else{
            e.printStackTrace();
            return Result.coderMsg(CodeMsg.SERVER_ERROR);
        }

    }






















}
